package com.nemodynamic.cattivial;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import com.nemodynamic.cattivial.R;
import com.nemodynamic.cattivial.UIElement.CattivialBackground;
import com.nemodynamic.cattivial.UIElement.CattivialFaceItemView;
import com.nemodynamic.cattivial.UIElement.CattivialFaceItemView.OnCativalFaceItemAction;
import com.nemodynamic.cattivial.beansElement.CattivialFaceItem;
import com.nemodynamic.cattivial.beansElement.Question;
import com.nemodynamic.cattivial.facebook.FacebookFriendItem;
import com.nemodynamic.cattivial.facebook.FacebookUtils;
import com.nemodynamic.cattivial.utils.DLog;
import com.nemodynamic.cattivial.utils.ImageUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.AsyncTask;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

public class CattivialGameTask extends AsyncTask<Integer, Object, ArrayList<FacebookFriendItem>> {
	private SoundPool soundPool;
	private static boolean isTaskRunning = false;
	private int speedFactor = 1;
	private int height = 0;
	private int width = 0;
	private int level = 1;
	private int baselevel = 4;
	private Context context;
	final private ViewGroup gameContainer;
	private TextView score;
	private TextView[] results;
	private TextView question;
	private ImageView startButton;
	private View startBox;
	private GameManager gameManager;
	private Animation loadAnimation;
	private View background;
	private boolean isSoundReady = false;
	private AudioManager audioManager;
	private float volume;
	private int win;
	private int fails;
	private int dragSound;
	private int eat;

	public CattivialGameTask(Context context, View startBox, ImageView startButton, TextView score, TextView question, TextView[] results, ViewGroup gameContainer, int level) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		width = (int) (display.getWidth() / (5 * (context.getResources().getDisplayMetrics().density >= 3.0 ? 1.2 : 1))); // deprecated
		height = width; // deprecated
		this.context = context;
		this.results = results;
		this.gameContainer = gameContainer;
		this.startButton = startButton;
		this.startBox = startBox;
		this.score = score;
		this.question = question;
		this.level = baselevel + level;
		initSound();
	}

	@Override
	protected void onPreExecute() {
		if (isTaskRunning) {
			cancel(true);
			return;
		} else {
			background = new CattivialBackground(context, R.drawable.bg3);
			background.setVisibility(View.INVISIBLE);
			gameContainer.addView(background);
			this.gameManager = GameManager.getNewInstance(context, this.level, gameContainer, results, question);
			if (this.gameManager == null) {
				cancel(true);
				return;
			} else {
				gameManager.setGameMusic(R.raw.game);
			}
		}
		isTaskRunning = true;

		if (startButton != null) {
			loadAnimation = AnimationUtils.loadAnimation(context, R.anim.statbutton_load);
			startButton.startAnimation(loadAnimation);
		}
		
		

	}

	@Override
	protected ArrayList<FacebookFriendItem> doInBackground(Integer... params) {
		if (gameManager != null && !isCancelled()) {

			ArrayList<FacebookFriendItem> familyItems = FacebookUtils.getFriends(context, params[0]);
			for (FacebookFriendItem facebookFamilyItem : familyItems) {
				try {
					if (context != null) {
						Object[] cattivialData = new Object[2];
						CattivialFaceItem cattivialFaceItem = new CattivialFaceItem(facebookFamilyItem.getId(), facebookFamilyItem.getName());
						Bitmap bitmap = BitmapFactory.decodeStream((new URL("http://graph.facebook.com/" + cattivialFaceItem.getId() + "/picture?width=" + width + "&height=" + height))
								.openConnection().getInputStream());
						bitmap = ImageUtils.getCroppedBitmap(bitmap);
						cattivialData[0] = cattivialFaceItem;
						cattivialData[1] = bitmap;
						publishProgress(cattivialData);
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return familyItems;
		} else {
			return null;
		}
	}

	@Override
	protected void onProgressUpdate(Object... cattivialData) {
		gameManager.addFaceItem(createFaceItemView(cattivialData));
	}

	@Override
	protected void onPostExecute(ArrayList<FacebookFriendItem> result) {
		if (!isCancelled() && gameManager.getFaceItemsSize() > 0) {
			setGameUI();
			float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
			float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
			volume = actualVolume / maxVolume;
			isTaskRunning = false;
			gameManager.startGame();
		}
	}

	private CattivialFaceItemView createFaceItemView(Object[] cattivialData) {
		CattivialFaceItem cattivialFaceItem = (CattivialFaceItem) cattivialData[0];
		generateQuestionResponse(cattivialFaceItem, level);
		final CattivialFaceItemView cattivalFaceItem = new CattivialFaceItemView(context, cattivialFaceItem, (Bitmap) cattivialData[1], gameContainer, results, level * speedFactor, soundPool,
				dragSound);
		cattivalFaceItem.setOnCativalFaceItemActionListener(new OnCativalFaceItemAction() {
			@Override
			public void onCorrectAnswer(final View v) {
				score.setText("" + CattivialFaceItemView.getScore());
				gameManager.removeFaceItem(v);
				if (isSoundReady) {
					float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
					float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
					volume = actualVolume / maxVolume;
					soundPool.play(win, volume, volume, 1, 0, 1f);
				}
				if (gameManager.getFaceItemsSize() == 0) {
					gameManager.stopGame(score.getText().toString());
					resetUI();
				} else {
					gameManager.nextQuestion();
				}
			}

			@Override
			public void onItemExpired(final View v) {

				gameManager.removeFaceItem(v);
				if (isSoundReady) {
					float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
					float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
					volume = actualVolume / maxVolume;
					soundPool.play(fails, volume, volume, 1, 0, 1f);
				}
				if (gameManager.getFaceItemsSize() == 0) {
					gameManager.stopGame(score.getText().toString());
					resetUI();
				} else {
					if (((CattivialFaceItemView) v).getFaceItem().isActive()) {
						gameManager.nextQuestion();
					}
				}
			}

			@Override
			public void onBadAnswer(View v) {

				gameManager.removeFaceItem(v);
				if (isSoundReady) {
					float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
					float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
					volume = actualVolume / maxVolume;
					soundPool.play(fails, volume, volume, 1, 0, 1f);
				}
				if (gameManager.getFaceItemsSize() == 0) {
					gameManager.stopGame(score.getText().toString());
					resetUI();
				} else {
					if (((CattivialFaceItemView) v).getFaceItem().isActive()) {
						gameManager.nextQuestion();
					}
				}

			}

			@Override
			public void onEat(View itemView) {
				float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
				float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
				volume = actualVolume / maxVolume;
				soundPool.play(eat, volume, volume, 1, 0, 1f);
			}

		});
		return cattivalFaceItem;
	}

	private void generateQuestionResponse(CattivialFaceItem faceItem, int level) {
		try {
			Question question =  QuestionFactory.createQuestion(1);
			faceItem.setQuestion(question.getQuestion());
			faceItem.setResults(question.getResults());
			faceItem.setRightResult(question.getRightResult());
			faceItem.setMaxTime(10);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void resetUI() {
		score.setVisibility(View.INVISIBLE);
		startBox.setVisibility(View.VISIBLE);
		results[0].setVisibility(View.INVISIBLE);
		results[1].setVisibility(View.INVISIBLE);
		results[2].setVisibility(View.INVISIBLE);
		score.setVisibility(View.INVISIBLE);
		background.setVisibility(View.INVISIBLE);
		question.setVisibility(View.GONE);
		question.clearAnimation();
	}

	private void setGameUI() {
		question.setVisibility(View.VISIBLE);
		score.setVisibility(View.VISIBLE);
		startBox.setVisibility(View.GONE);
		results[0].setVisibility(View.VISIBLE);
		results[1].setVisibility(View.VISIBLE);
		results[2].setVisibility(View.VISIBLE);
		score.setVisibility(View.VISIBLE);
		background.setVisibility(View.VISIBLE);
		if (startButton != null) {
			startButton.clearAnimation();
		}

	}

	private void initSound() {
		this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		volume = actualVolume / maxVolume;
		soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
		soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
			@Override
			public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
				isSoundReady = true;
			}
		});
		win = soundPool.load(context, R.raw.win, 1);
		fails = soundPool.load(context, R.raw.lose, 1);
		eat = soundPool.load(context, R.raw.eat, 1);
		dragSound = soundPool.load(context, R.raw.tic, 1);
	}
}
